<template>
  <div class="staff-form">
    <el-card>
      <h2>{{ isEdit ? '编辑人员' : '新增人员' }}</h2>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" style="max-width:500px;">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="form.realName" />
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-input v-model="form.department" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role">
            <el-option value="管理员" label="管理员" />
            <el-option value="经理" label="经理" />
            <el-option value="客服" label="客服" />
            <el-option value="普通员工" label="普通员工" />
          </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="form.password" type="password" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { addStaff, updateStaff, getStaff } from '@/api/staff'

const router = useRouter()
const route = useRoute()
const formRef = ref()
const isEdit = ref(false)
const form = ref({
  username: '',
  realName: '',
  department: '',
  phone: '',
  email: '',
  role: '普通员工',
  password: ''
})
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入电话', trigger: 'blur' }]
}

onMounted(async () => {
  if (route.params.id) {
    isEdit.value = true
    const res = await getStaff(route.params.id)
    Object.assign(form.value, res)
    form.value.password = ''
  }
})

const handleSubmit = async () => {
  await formRef.value.validate()
  if (isEdit.value) {
    await updateStaff(form.value)
    ElMessage.success('修改成功')
  } else {
    await addStaff(form.value)
    ElMessage.success('新增成功')
  }
  router.push('/staff')
}
const goBack = () => router.push('/staff')
</script>

<style scoped>
.staff-form {
  padding: 32px 0;
}
</style> 